package com.mojo.concurrent.customerproducer;

/**
 * 生产者
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class Producer implements Runnable {
    final Resource resource;

    public Producer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        for (; ; ) {
            synchronized (resource) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //还有资源就等待
                if (resource.hasResource) {
                    System.out.println(Thread.currentThread().getName() + "+++还有，等待消费++");
                    try {
                        resource.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + "producer>>>我来生产资源");
                    resource.hasResource = true;
                    //等待被消费
                    resource.notifyAll();
                }
                System.out.println("=============================================");
            }
        }
    }
}
